package serlvet;

import com.sun.prism.impl.Disposer.Record;
import dao.DaoService;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;

/**
 * Create By IntelliJ IDEA
 *
 * @Author: jsonor
 * @Create-Time: 2017/9/25 15:31
 * @Description: 返回用户的登录信息
 */
public class RecordServlet extends HttpServlet {

  private static final Logger logger = Logger.getLogger(RecordServlet.class);
  private DaoService daoService = new DaoService();
  private int visitNumber;

  @Override
  public void init() throws ServletException {
    // 从数据库中读取以后的访问记录
    try {
      visitNumber = daoService.getCount();
    } catch (SQLException e) {
      logger.warn(e);
      throw new ExceptionInInitializerError(e);
    }
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    doPost(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    visitNumber++;
    logger.warn("Visit Number " + visitNumber);
    resp.getWriter().write("you are the " + visitNumber + " visitor!");
  }

  @Override
  public void destroy() {
    // 将用户访问数量写回到数据库中
    try {
      daoService.saveCount(visitNumber);
    } catch (SQLException e) {
      logger.warn(e);
    }
  }
}
